﻿using Aliyun.Acs.Core;
using Aliyun.Acs.Core.Http;
using Aliyun.Acs.Core.Profile;
using BridgeWeChat.Model;
using BridgeWebSystemLib.Core.Util;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using WeChatCommon.BizLogic;

namespace BridgeWeChatApiService.Controllers
{
    /// <summary>
    /// 阿里云短信
    /// </summary>
    [ApiController]
    public class AliYunSMSController: ControllerBase
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="requestParam"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("AliYunSendSMS")]
        public string AliYunSendSMS(AliYunSendSMSRequest requestParam)
        {
            BaseResponse response = new BaseResponse();
            var msgInfo = RequestHelper.NotnullValidate(requestParam);
            if (!msgInfo.State)
            {
                response.ResultCode = "-1";
                response.ResultMessage = msgInfo.Message;
                return JsonUtil.JsonSerializeObject(response);
            }

            string keyID = HPDHttpContext.AppSettings.Value.AliYunSMS.AccessKeyID;
            string secret = HPDHttpContext.AppSettings.Value.AliYunSMS.AccessKeySecret;
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", keyID, secret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest commonRequest = new CommonRequest();
            commonRequest.Method = MethodType.POST;
            commonRequest.Domain = "dysmsapi.aliyuncs.com";
            commonRequest.Version = "2017-05-25";
            commonRequest.Action = "SendSms";
            // request.Protocol = ProtocolType.HTTP;
            commonRequest.AddQueryParameters("PhoneNumbers", requestParam.PhoneNumbers);
            commonRequest.AddQueryParameters("SignName", requestParam.SignName);
            commonRequest.AddQueryParameters("TemplateCode", requestParam.TemplateCode);
            commonRequest.AddQueryParameters("TemplateParam", requestParam.TemplateParam);
            try
            {
                CommonResponse comResponse = client.GetCommonResponse(commonRequest);
                string responseString = System.Text.Encoding.Default.GetString(comResponse.HttpResponse.Content);
                LogUtil.WriteLog(responseString);

                var tmResponse = JsonUtil.JsonDeserialize<SendSMSResponse>(responseString);
                if (tmResponse.Code == "OK")
                {
                    msgInfo = AyMessageUtil.SaveAliYunMessage(requestParam, tmResponse);
                    if (!msgInfo.State)
                    {
                        response.ResultCode = "-1";
                        response.ResultMessage = msgInfo.Message;
                    }
                }
                else
                {
                    response.ResultCode = "-1";
                    response.ResultMessage = tmResponse.Message;
                }
            }
            catch (Exception e)
            {
                LogUtil.WriteLog(e.Message);
            }
            return JsonUtil.JsonSerializeObject(response);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="requestParams"></param>
        /// <returns></returns>
        [AllowAnonymous]
        [HttpPost("AliYunBatchSendSMS")]
        public string AliYunBatchSendSMS(List<AliYunSendSMSRequest> requestParams)
        {
            BaseResponse response = new BaseResponse();
            foreach (var param in requestParams)
            {
                var msgInfo = RequestHelper.NotnullValidate(param);
                if (!msgInfo.State)
                {
                    response.ResultCode = "-1";
                    response.ResultMessage = msgInfo.Message;
                    return JsonUtil.JsonSerializeObject(response);
                }
            }
            
            string keyID = HPDHttpContext.AppSettings.Value.AliYunSMS.AccessKeyID;
            string secret = HPDHttpContext.AppSettings.Value.AliYunSMS.AccessKeySecret;
            IClientProfile profile = DefaultProfile.GetProfile("cn-hangzhou", keyID, secret);
            DefaultAcsClient client = new DefaultAcsClient(profile);
            CommonRequest request = new CommonRequest();
            request.Method = MethodType.POST;
            request.Domain = "dysmsapi.aliyuncs.com";
            request.Version = "2017-05-25";
            request.Action = "SendBatchSms";
            // request.Protocol = ProtocolType.HTTP;
            string[] phoneNumbersArray = requestParams.Select(t => t.PhoneNumbers).ToArray();
            var jsonPhoneNumbersArray = JsonUtil.JsonSerializeObject(phoneNumbersArray);
            request.AddQueryParameters("PhoneNumberJson", jsonPhoneNumbersArray);

            string[] signNameArray = requestParams.Select(t => t.SignName).ToArray();
            var jsonSignNameArray = JsonUtil.JsonSerializeObject(signNameArray);
            request.AddQueryParameters("SignNameJson", jsonSignNameArray);

            request.AddQueryParameters("TemplateCode", requestParams.First().TemplateCode);

            string[] templateParamArray = requestParams.Select(t => t.TemplateParam).ToArray();
            var jsontemplateParamArray = JsonUtil.JsonSerializeObject(templateParamArray);
            request.AddQueryParameters("TemplateParamJson", jsontemplateParamArray);
            //request.AddQueryParameters("SmsUpExtendCodeJson", "123");
            try
            {
                CommonResponse comResponse = client.GetCommonResponse(request);
                string responseString = System.Text.Encoding.Default.GetString(comResponse.HttpResponse.Content);
                LogUtil.WriteLog(responseString);

                var tmResponse = JsonUtil.JsonDeserialize<SendSMSResponse>(responseString);
                if (tmResponse.Code == "OK")
                {
                    var msgInfo = AyMessageUtil.BatchSaveAliYunMessage(requestParams, tmResponse);
                    if (!msgInfo.State)
                    {
                        response.ResultCode = "-1";
                        response.ResultMessage = msgInfo.Message;
                    }
                }
                else
                {
                    response.ResultCode = "-1";
                    response.ResultMessage = tmResponse.Message;
                }
            }
            catch (Exception e)
            {
                LogUtil.WriteLog(e.Message);
            }
            return JsonUtil.JsonSerializeObject(response);
        }
    }
}
